import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

/// 图片选择工具类
class ImagePickerUtil {
  static final ImagePicker _picker = ImagePicker();

  /// 直接从相册选择图片（简化版本）- 用于头像
  static Future<String?> pickImageFromGallery() async {
    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 512,
        maxHeight: 512,
        imageQuality: 80,
      );

      if (image != null) {
        return await _saveAvatarImageToLocal(image);
      }
      return null;
    } catch (e) {
      debugPrint('Failed to pick image from gallery: $e');
      return null;
    }
  }

  /// 直接从相册选择图片（用于时间胶囊）
  static Future<String?> pickImageFromGalleryForTimeCapsule() async {
    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 512,
        maxHeight: 512,
        imageQuality: 80,
      );

      if (image != null) {
        return await _saveTimeCapsuleImageToLocal(image);
      }
      return null;
    } catch (e) {
      debugPrint('Failed to pick image from gallery: $e');
      return null;
    }
  }

  /// 保存头像图片到本地
  static Future<String?> _saveAvatarImageToLocal(XFile image) async {
    try {
      // 获取应用文档目录
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String avatarsDir = path.join(appDocDir.path, 'avatars');

      // 创建头像目录
      final Directory avatarDirectory = Directory(avatarsDir);
      if (!await avatarDirectory.exists()) {
        await avatarDirectory.create(recursive: true);
      }

      // 生成唯一文件名
      final String fileName =
          'avatar_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final String filePath = path.join(avatarsDir, fileName);

      // 复制文件到目标位置
      final File sourceFile = File(image.path);
      await sourceFile.copy(filePath);

      // 返回完整路径（头像使用绝对路径）
      return filePath;
    } catch (e) {
      debugPrint('Failed to save avatar image: $e');
      return null;
    }
  }

  /// 保存时间胶囊图片到本地
  static Future<String?> _saveTimeCapsuleImageToLocal(XFile image) async {
    try {
      // 获取应用文档目录
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String timeCapsuleImagesDir = path.join(
        appDocDir.path,
        'time_capsule_images',
      );

      // 创建时间胶囊图片目录
      final Directory imageDirectory = Directory(timeCapsuleImagesDir);
      if (!await imageDirectory.exists()) {
        await imageDirectory.create(recursive: true);
      }

      // 生成唯一文件名
      final String fileName =
          'time_capsule_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final String filePath = path.join(timeCapsuleImagesDir, fileName);

      // 复制文件到目标位置
      final File sourceFile = File(image.path);
      await sourceFile.copy(filePath);

      // 返回相对路径而不是绝对路径
      final relativePath = 'time_capsule_images/$fileName';
      return relativePath;
    } catch (e) {
      debugPrint('❌ Failed to save time capsule image: $e');
      return null;
    }
  }

  /// 直接从相册选择图片（用于聊天）
  static Future<String?> pickImageFromGalleryForChat() async {
    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1024,
        maxHeight: 1024,
        imageQuality: 85,
      );

      if (image != null) {
        return await _saveChatImageToLocal(image);
      }
      return null;
    } catch (e) {
      debugPrint('Failed to pick image from gallery for chat: $e');
      return null;
    }
  }

  /// 保存聊天图片到本地
  static Future<String?> _saveChatImageToLocal(XFile image) async {
    try {
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String chatImagesDir = path.join(appDocDir.path, 'chat_images');

      // 创建聊天图片目录
      final Directory chatImagesDirObj = Directory(chatImagesDir);
      if (!await chatImagesDirObj.exists()) {
        await chatImagesDirObj.create(recursive: true);
      }

      // 生成唯一文件名
      final String fileName =
          'chat_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final String filePath = path.join(chatImagesDir, fileName);

      // 复制文件到目标位置
      final File sourceFile = File(image.path);
      await sourceFile.copy(filePath);

      // 返回相对路径而不是绝对路径
      final relativePath = 'chat_images/$fileName';
      return relativePath;
    } catch (e) {
      debugPrint('❌ Failed to save chat image: $e');
      return null;
    }
  }

  /// 根据相对路径获取完整的文件路径
  static Future<String?> getFullImagePath(String relativePath) async {
    try {
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String fullPath = path.join(appDocDir.path, relativePath);

      // 检查文件是否存在
      final File file = File(fullPath);
      final exists = await file.exists();

      if (exists) {
        return fullPath;
      }
      return null;
    } catch (e) {
      debugPrint('❌ Failed to get full image path: $e');
      return null;
    }
  }
}
